package hero.mps.web.system_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import hero.mps.utils.ResultUtils;
import hero.mps.utils.ResultVo;
import hero.mps.web.sys_role.entity.SysRole;
import hero.mps.web.sys_role.service.SysRoleService;
import hero.mps.web.sys_user_role.entity.SysUserRole;
import hero.mps.web.sys_user_role.service.SysUserRoleService;
import hero.mps.web.system_user.entity.PageParam;
import hero.mps.web.system_user.entity.SysUser;
import hero.mps.web.system_user.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/user")
public class SysUserController {
    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final SysUserRoleService sysUserRoleService;

    /**
     * 新增用户
     * @param sysUser
     * @return
     */
    @PostMapping
    public ResultVo addUser(@RequestBody SysUser sysUser) {
        LambdaQueryWrapper<SysUser> query = Wrappers.lambdaQuery(SysUser.class)
                .eq(SysUser::getUsername, sysUser.getUsername());
        SysUser user = sysUserService.getOne(query);
        if (user != null) {
            return ResultUtils.error("账户被占用");
        }
        // 加密
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        sysUser.setIsAdmin(0);
        sysUser.setCreateTime(new Date());
        sysUserService.add(sysUser);
        return ResultUtils.success("新增用户成功");
    }

    /**
     * 修改用户
     * @param sysUser
     * @return
     */
    @PutMapping
    public ResultVo editUser(@RequestBody SysUser sysUser) {
        LambdaQueryWrapper<SysUser> query = Wrappers.lambdaQuery(SysUser.class)
                .eq(SysUser::getUsername, sysUser.getUsername());
        SysUser user = sysUserService.getOne(query);
        Boolean save = true;
        if (user != null) {
            // 加密
            sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
            sysUser.setIsAdmin(0);
            sysUser.setUserId(user.getUserId());
            sysUser.setUpdateTime(new Date());
            sysUserService.edit(sysUser);

        }
        return ResultUtils.success("编辑用户成功");

    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("/{userId}")
    public ResultVo deleteUser(@PathVariable("userId") Long userId) {
        boolean remove = sysUserService.removeById(userId);
        if (remove) {
            return ResultUtils.success("删除用户成功");
        }
        return ResultUtils.error("删除用户失败");
    }

    /**
     * 获取用户列表
     * @param nickName
     * @param phone
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public ResultVo getList(@RequestParam(required = false) String nickName,
                            @RequestParam(required = false) String phone,
                            @RequestParam(defaultValue = "1") long currentPage,
                            @RequestParam(defaultValue = "10") long pageSize){
        PageParam pageParam = new PageParam();
        pageParam.setCurrentPage(currentPage);
        pageParam.setPageSize(pageSize);
        pageParam.setNickName(nickName);
        pageParam.setPhone(phone);
        IPage<SysUser> list = sysUserService.list(pageParam);
        list.getRecords().stream().forEach(item->{
            item.setPassword("");
        });
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 获取角色列表
     * @return
     */
    @GetMapping("roleList")
    public ResultVo getRoleList(){
        List<SysRole> roleList = sysRoleService.list();
        return ResultUtils.success("查询成功", roleList);
    }

    @GetMapping("/role")
    public ResultVo getRoleByUserId(@RequestParam Long userId){
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getUserId, userId);
        SysUserRole sysUserRole = sysUserRoleService.getOne(queryWrapper);
        return ResultUtils.success("查询成功", sysUserRole);
    }
}
